<script setup lang="ts">
import { ElMessage } from 'element-plus'
import Hls from 'hls.js'
import BlockHead from './block-head.vue'

defineOptions({
  name: 'ItemFour',
})

const videoRef = ref<HTMLVideoElement>()

let player: Hls | null = null
const error = ref(false)

let count = 0

function createPlayer() {
  if (videoRef.value && Hls.isSupported()) {
    player = new Hls({
      // debug: true,
      maxBufferHole: 2, // 默认 0.5 秒
    })

    try {
      player.loadSource(`${location.origin}/hls/stream.m3u8`)
    }
    catch (error) {
      console.error(error)
    }
    player.attachMedia(videoRef.value)

    // 监听事件（可选）
    player.on(Hls.Events.MANIFEST_PARSED, () => {
      console.info('HLS 流已加载，准备播放')
      videoRef.value?.play().catch(e => console.error('自动播放失败:', e))
    })

    // player.on(Hls.Events.FRAG_BUFFERED, (event, data) => {
    //   console.info('Fragment ID:', data.id)
    //   console.info('Fragment buffered:', data.frag)
    //   console.info('Loading stats:', data.stats)
    // })

    player.on(Hls.Events.ERROR, (event, data) => {
      count++
      if (count > 15) {
        ElMessage.error('无法恢复播放器，正在刷新页面')
        // location.reload()
        return
      }
      console.error('Fatal error:', data)
      switch (data.type) {
        case Hls.ErrorTypes.NETWORK_ERROR:
          console.info('Attempting to recover from network error...')
          player?.startLoad() // 尝试重新加载
          break
        case Hls.ErrorTypes.MEDIA_ERROR:
          console.info('Attempting to recover from media error...')
          player?.recoverMediaError() // 尝试恢复媒体错误
          videoRef.value?.play().catch(e => console.error('自动播放失败:', e))
          break
        default:
          // 无法恢复，销毁并重新初始化
          player?.off(Hls.Events.MANIFEST_PARSED)
          player?.off(Hls.Events.ERROR)
          player?.off(Hls.Events.FRAG_LOADED)
          player?.destroy()
          createPlayer() // 重新初始化播放器
          break
      }
    })

    player.on(Hls.Events.FRAG_LOADED, () => {
      error.value = false
    })
  }
}

function destroyPlayer() {
  if (player) {
    player.destroy()
    player = null
  }
}

onBeforeUnmount(() => {
  destroyPlayer()
})

onMounted(() => {
  createPlayer()
})
</script>

<template>
  <div class="flex flex-auto flex-col">
    <BlockHead title="视频监控看板" />
    <div class="block-body h-70 w-full flex-auto items-center">
      <div class="relative h-full w-full p-3">
        <video ref="videoRef" controls autoplay loop muted class="h-full w-full object-fill" />
        <div v-if="false" class="absolute inset-0 h-full w-full flex items-center justify-center bg-black text-center text-sm opacity-50">
          获取失败
        </div>
      </div>
    </div>
  </div>
</template>
